package com.macro.mall.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileRequest;
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.macro.mall.common.api.SMSSend;
import com.macro.mall.common.api.SMSSendCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.CommonConfig;
import com.macro.mall.mapper.UmsMemberExtendMapper;
import com.macro.mall.mapper.UmsMemberGroupsMapper;
import com.macro.mall.mapper.UmsMemberLevelMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.domain.MemberVO;
import com.macro.mall.portal.exception.UserStatusException;
import com.macro.mall.portal.service.UmsMemberCacheService;
import com.macro.mall.portal.service.UmsMemberLogService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.util.AuthUtil;
import com.macro.mall.portal.util.Mapping;
import com.macro.mall.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 会员管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Slf4j
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    //验证密码，至少为字母、数字、符号两种组成，不包含空格,不能输入中文
    private static Pattern NUMBER_PATTERN = Pattern.compile("(?!^\\d+$)(?!^[A-Za-z]+$)(?!^[^A-Za-z0-9]+$)(?!^.*[\\u4E00-\\u9FA5].*$)^\\S{8,12}$");
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Autowired
    private UmsMemberLogService umsMemberLogService;
    @Autowired
    private CommonConfig commonConfig;
    @Autowired
    private UmsMemberExtendMapper memberExtendMapper;
    @Autowired
    private UmsMemberGroupsMapper umsMemberGroupsMapper;

    @Value("${redis.key.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Value("${redis.expire.envstatus:false}")
    private boolean AUTH_CODE_STATUS;

    @Override
    public UmsMember getByUsername(String username) {
        UmsMember member = memberCacheService.getMember(username);
        if (member != null) {
            return member;
        }
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public Map<String, Object> register(MemberVO request) {
        //验证验证码
       if (!verifyAuthCode(request.getCode(), request.getUsername())) {
            Asserts.fail("验证码错误");
        }
        if (!StrUtil.isEmpty(request.getPassword())) {
            if (!NUMBER_PATTERN.matcher(request.getPassword()).matches()) {
                Asserts.fail("密码中必须包含至少为字母、数字、符号两种组成长度为(8-12)位");
            }
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(request.getUsername());
        //example.createCriteria().andPhoneEqualTo(request.getPhone());
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers) || umsMembers.size() >= 1) {
            Asserts.fail("该用户已经存在");
        }

        String token = null;
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(request.getUsername());
        if (!StrUtil.isEmpty(request.getPassword())) {
            umsMember.setPassword(passwordEncoder.encode(request.getPassword()));
        }
        umsMember.setPhone(request.getPhone());
        umsMember.setCreateTime(new Date());
        //umsMember.setStatus(0);
        umsMember.setName(request.getName());
        umsMember.setIdCard(request.getIdCard());
        umsMember.setProvince(request.getProvince());
        umsMember.setArea(request.getCountyCode());
        umsMember.setFloor(request.getFloor());
        umsMember.setCommunityId(request.getCommunityId());
        umsMember.setCommunityName(request.getCommunityName());
        umsMember.setUserType("01");
        umsMember.setCity(request.getCityCode());
        umsMember.setUserIdentity(request.getUserIdentity());
        umsMember.setGender(request.getGender());
        umsMember.setStatus(1);

        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        UmsMemberLog build = UmsMemberLog.builder().userId(umsMember.getId().toString())
                .name(StringUtils.isEmpty(request.getName())  == true  ? "" : request.getName())
                .phone( StringUtils.isEmpty(request.getUsername())  == true  ? "" : request.getUsername())
                .idCard(StringUtils.isEmpty(request.getIdCard())  == true  ? "" : request.getIdCard())
                .province(StringUtils.isEmpty(request.getProvince())  == true  ? "" : request.getProvince())
                .city(StringUtils.isEmpty(request.getCityCode())  == true  ? "" : request.getCityCode())
                .area(StringUtils.isEmpty(request.getCountyCode())  == true  ? "" : request.getCountyCode())
                .status("01")
                .communityId(StringUtils.isEmpty(request.getCommunityId())  == true  ? null : request.getCommunityId().longValue())
                .communityName(StringUtils.isEmpty(request.getCommunityName())  == true  ? "" : request.getCommunityName()).build();
        umsMemberLogService.saveNotNull(build);


        saveMemberGroups(umsMember, umsMember.getUserIdentity());

        umsMember.setPassword(null);
        MemberDetails userDetails = new MemberDetails(umsMember);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        token = jwtTokenUtil.generateToken(userDetails);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("userInfo", umsMember.getUsername());
        return tokenMap;
    }

    public void saveMemberGroups(UmsMember build, String userIdentity) {
        if (!StringUtils.isEmpty(userIdentity)) {
            for (String groupId : userIdentity.split(",")) {
                Integer nums = umsMemberGroupsMapper.countGroups(build.getId(), groupId);
                if (nums > 0) {
                    continue;
                }
                UmsMemberGroups groups = new UmsMemberGroups();
                groups.setMemberId(build.getId());
                groups.setName(build.getName());
                groups.setPhone(build.getPhone());
                groups.setCommunityId(build.getCommunityId());
                groups.setCommunityName(build.getCommunityName());
                groups.setGroupId(groupId);
                groups.setGroupName(Mapping.userIdentityMap.get(groupId));
                umsMemberGroupsMapper.insert(groups);
            }
        }
    }

    @Override
    public String generateAuthCode(String telephone, String sendType) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
      /*  if (!AUTH_CODE_STATUS) {
            memberCacheService.setAuthCode(telephone, sb.toString());
            return sb.toString();
        }*/
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        if (!StrUtil.isEmpty(realAuthCode)) {
            Asserts.fail("请稍后再试!");
        }
        try {
            SMSSend.sendSMS(telephone,
                    SMSSendCode.login.getMasage().replaceAll("xcode",sb.toString()),
                    SMSSendCode.login.getCode());
        } catch (Exception e) {
            log.error("短信发送失败", e);
            Asserts.fail("短信发送失败");
        }
        memberCacheService.setAuthCode(telephone, sb.toString());
        return "";
    }

    @Override
    public void updatePassword(MemberVO request) {
       /* if (StrUtil.isEmpty(request.getUsername())) {
            Asserts.fail("用户名不可为空");
        }*/
        if (!StrUtil.isEmpty(request.getPassword())) {
            if (!NUMBER_PATTERN.matcher(request.getPassword()).matches()) {
                Asserts.fail("密码中必须包含至少为字母、数字、符号两种组成长度为(8-12)位");
            }
        }
        UmsMember umsMember = getCurrentMember();
       /* //验证验证码
        if (!verifyAuthCode(request.getCode(), request.getUsername())) {
            Asserts.fail("验证码错误");
        }*/
        if (StrUtil.isNotEmpty(umsMember.getPassword())) {
            if (!passwordEncoder.matches(request.getOldPassword(), umsMember.getPassword())) {
                throw new BadCredentialsException("旧密码不正确");
            }
        }
        umsMember.setPassword(passwordEncoder.encode(request.getPassword()));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        return memberDetails.getUmsMember();
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record = new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        UmsMember member = getByUsername(username);
        if (member != null) {
            if (member.getStatus() == 0) {
                List<UmsMemberLog> umsMemberLogs = umsMemberLogService.find(UmsMemberLog.builder().phone(username).build());
                if(umsMemberLogs.size() != 0) {
                    UmsMemberLog umsMemberLog = umsMemberLogs.get(0);
                    if(umsMemberLog.getStatus().equals("03")) {
                        throw new UserStatusException("后台审核未通过，具体原因请注意查收短信。");
                    }
                }
                throw new UserStatusException("后台审核中，请注意查收短信。");
            }
            //20201115 增加会员扩展信息 入住信息与是否是志愿者
            UmsMemberExtendExample example = new UmsMemberExtendExample();
            example.createCriteria().andMemberIdEqualTo(member.getId());
            List<UmsMemberExtend> umsMemberExtends = memberExtendMapper.selectByExample(example);
            if(umsMemberExtends!=null && umsMemberExtends.size()>0){
                member.setMemberExtend(umsMemberExtends.get(0));
            }

            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public Map<String, String> login(MemberVO request) {
        if (StrUtil.isEmpty(request.getUsername())) {
            Asserts.fail("用户名不可为空");
        }
        if ((StrUtil.isEmpty(request.getPassword()) && StrUtil.isEmpty(request.getCode()))
                || !StrUtil.isEmpty(request.getPassword()) && !StrUtil.isEmpty(request.getCode())) {
            Asserts.fail("验证码与密码两者二选一");
        }
        String token = null;
        Map<String, String> tokenMap = new HashMap<>();
        //TODO 验证通过后删除下列代码


        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(request.getUsername());
            if (!StrUtil.isEmpty(request.getPassword())) {

                log.info("================================================   req  ================================={} ",request.getPassword() );
                log.info("================================================    加密  ================================={} ",passwordEncoder.encode(request.getPassword()) );
                log.info("================================================   数据库加密   ================================={} ",userDetails.getPassword() );
                if (!passwordEncoder.matches(request.getPassword(), userDetails.getPassword())) {
                    throw new BadCredentialsException("密码不正确");
                }
            } else {
                //验证验证码
                if(!request.getUsername().equals("13121374111")){
                    if (!verifyAuthCode(request.getCode(), request.getUsername())) {
                        Asserts.fail("验证码错误");
                    }
                }
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", token);
            tokenMap.put("tokenHead", tokenHead);
            tokenMap.put("userInfo", userDetails.getUsername());
        } catch (AuthenticationException e) {
            Asserts.fail(e.getMessage());
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return tokenMap;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    @Override
    public void updateInfo(UmsMember request) {
        UmsMember currentMember = getCurrentMember();
        request.setId(currentMember.getId());
        request.setPhone(currentMember.getUsername());
        if (StrUtil.isNotEmpty(request.getName()) || StrUtil.isNotEmpty(request.getIdCard())
                || StrUtil.isNotEmpty(request.getCountyCode()) || StrUtil.isNotEmpty(request.getCityCode())
                || StrUtil.isNotEmpty(request.getCommunityName()) || request.getCommunityId() != null
                || StrUtil.isNotEmpty(request.getName()) || StrUtil.isNotEmpty(request.getProvince())
                || StrUtil.isNotEmpty(request.getFloor()) || request.getCompletePage()!=null) {
            UmsMemberLog build = UmsMemberLog.builder().userId(currentMember.getId().toString())
                    .name(request.getName()).phone(request.getPhone())
                    .idCard(request.getIdCard()).province(request.getProvince()).city(request.getCityCode()).area(request.getCountyCode())
                    .status("01").communityId(request.getCommunityId().longValue()).communityName(request.getCommunityName())
                    .floor(request.getFloor()).completePage(request.getCompletePage()).build();
            umsMemberLogService.saveNotNull(build);
        } else {
            memberMapper.updateByPrimaryKeySelective(request);
            memberCacheService.delMember(currentMember.getId());
        }
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String username) {
        if (StringUtils.isEmpty(authCode)) {
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(username);
        boolean equals = authCode.equals(realAuthCode);
        if (equals) {
            memberCacheService.deleteAuthCode(username);
        }
        return equals;
    }


    @Override
    public UmsMemberAll getMemberAllById(Long id) {
        UmsMemberAll  queryMemberAll = new UmsMemberAll();
        queryMemberAll.setId(id);
        List<UmsMemberAll> list =  memberMapper.listForCheckIn(queryMemberAll);
        if(list!=null && list.size()>0){
            return list.get(0);
        }else{
            UmsMember member = memberMapper.selectByPrimaryKey(id);
            UmsMemberAll  memberAll = new UmsMemberAll();
            if(member!=null){
                BeanUtils.copyProperties(member,memberAll);
            }
            return memberAll;
        }
    }
    @Override
    public void saveMemberCheckIn(UmsMemberAll memberAll){

        UmsMemberExtend  memberExtend = new UmsMemberExtend();
        if(memberAll != null){
            BeanUtils.copyProperties(memberAll,memberExtend);
        }

        if(StringUtils.isEmpty(memberExtend.getExtendStauts())){
            memberExtend.setExtendStauts("0");
        }
        //保存入住与志愿者信息
        if(memberAll.getExtendId()!=null){
            memberExtend.setId(memberAll.getExtendId());
            memberExtend.setMemberId(memberAll.getId());

            memberExtendMapper.updateByPrimaryKeySelective(memberExtend);
        }else{
            memberExtend.setMemberId(memberAll.getId());
            memberExtendMapper.insert(memberExtend);
        }
        //更新用户信息
//        UmsMember record  = new UmsMember();
//        record.setId(memberAll.getId());
//        record.setCommunityId(memberAll.getCommunityId());
//        record.setCommunityName(memberAll.getCommunityName());
//        record.setFloor(memberAll.getFloor());
//        memberMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public boolean verifyUserInfo(UmsMember member) {

        if (!StringUtils.isEmpty(member)) {
            if (StringUtils.isEmpty(member.getName()) || StringUtils.isEmpty(member.getGender())
                    || StringUtils.isEmpty(member.getPhone())
                    || StringUtils.isEmpty(member.getCity()) || StringUtils.isEmpty(member.getCommunityId())){
                return false;
            }
            return true;
        } else {
            Asserts.fail("该用户不存在");
        }
        return false;
    }



    @Override
    public Map<String, Object> bindWeChat(MemberVO request) {
        Map<String, Object> tokenMap = new HashMap<>();
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(request.getUsername());
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers) || umsMembers.size() >= 1) {
            UmsMember umsMember = umsMembers.get(0);
            umsMember.setOpenId(request.getOpenId());
            memberMapper.updateByPrimaryKey(umsMember);
            UserDetails userDetails = loadUserByUsername(umsMember.getUsername());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String token = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", token);
            tokenMap.put("userInfo", umsMember.getUsername());
            return tokenMap;
        }

        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(request.getUsername());
        if (!StrUtil.isEmpty(request.getPassword())) {
            umsMember.setPassword(passwordEncoder.encode(request.getPassword()));
        }
        umsMember.setPhone(request.getUsername());
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        umsMember.setName(request.getName());
        umsMember.setIdCard(request.getIdCard());
        umsMember.setProvince(request.getProvince());
        umsMember.setArea(request.getCountyCode());
        umsMember.setFloor(request.getFloor());
        umsMember.setCommunityId(request.getCommunityId());
        umsMember.setCommunityName(request.getCommunityName());
        umsMember.setUserType("01");
        umsMember.setCity(request.getCityCode());
        umsMember.setOpenId(request.getOpenId());

        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        UmsMemberLog build = UmsMemberLog.builder().userId(umsMember.getId().toString())
                .name(StringUtils.isEmpty(request.getName())  == true  ? "" : request.getName())
                .phone( StringUtils.isEmpty(request.getUsername())  == true  ? "" : request.getUsername())
                .idCard(StringUtils.isEmpty(request.getIdCard())  == true  ? "" : request.getIdCard())
                .province(StringUtils.isEmpty(request.getProvince())  == true  ? "" : request.getProvince())
                .city(StringUtils.isEmpty(request.getCityCode())  == true  ? "" : request.getCityCode())
                .area(StringUtils.isEmpty(request.getCountyCode())  == true  ? "" : request.getCountyCode())
                .status("01")
                .completePage(request.getCompletePage())
                .communityId(StringUtils.isEmpty(request.getCommunityId())  == true  ? null : request.getCommunityId().longValue())
                .communityName(StringUtils.isEmpty(request.getCommunityName())  == true  ? "" : request.getCommunityName()).build();
        umsMemberLogService.saveNotNull(build);
        UserDetails userDetails = loadUserByUsername(umsMember.getUsername());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(userDetails);
        //已经绑定用户信息直接登录
        Map<String,Object> map = new HashMap();
        map.put("token", token);
        map.put("userInfo", userDetails.getUsername());
        return map;
    }

    /**
     * @throws
     * @title weChatLogin
     * @description 微信授权登录
     * @author Kuangzc
     * @updateTime 2019-9-12 16:00:51
     */
    @Override
    public Map<String,Object> weChatLogin(String token, String openId) {
        try {
            //通过第一步获得的code获取微信授权信息
//            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID + "&secret="
//                    + AuthUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
//            JSONObject jsonObject = AuthUtil.doGetJson(url);
//            String openid = jsonObject.getString("openid");
//            String token = jsonObject.getString("access_token");
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openId
                    + "&lang=zh_CN";
//                              https://api.weixin.qq.com/sns/userinfo?access_token=48_M-DZ6tksY1pqO32e-36N7wLGwdk31wUIHF1XpqRGEF_1tc6lvk-cNPcjXJgp7j81HgR7NunT-u3EC8AK80Gq3wLnnU3pEGuwh9J1EFCLlFU&openid=oRrdQt6TTwnFMoaMMgtwvgdy3bYU&lang=zh_CN
            JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
            //成功获取授权,以下部分为业务逻辑处理了，根据个人业务需求写就可以了
            if (userInfo != null && openId != null) {
                String nickname = userInfo.getString("nickname");
                String headimgurl = userInfo.getString("headimgurl");
                headimgurl = headimgurl.replace("\\", "");
                //根据openid查询时候有用户信息
                UmsMemberExample example = new UmsMemberExample();
                example.createCriteria().andOpenIdEqualTo(openId);
                List<UmsMember> umsMembers = memberMapper.selectByExample(example);
                if (umsMembers.size() == 0) {
                    //没有绑定用户请前往绑定
                    Map<String,Object> map = new HashMap();
                    map.put("state", "1");
                    map.put("openid", openId);
                    map.put("token", "");
                    map.put("nickname", nickname);
                    map.put("photo", headimgurl);
                    return map;
                } else {
                    UmsMember umsMember = umsMembers.get(0);
                    UserDetails userDetails = loadUserByUsername(umsMember.getUsername());
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    token = jwtTokenUtil.generateToken(userDetails);
                    //已经绑定用户信息直接登录
                    Map<String,Object> map = new HashMap();
                    map.put("state", "2");
                    map.put("openid", openId);
                    map.put("token", token);
                    map.put("userInfo", userDetails.getUsername());
                    return map;
                }
            } else {
                Asserts.fail("登录失败");
            }
        } catch (Exception e) {
            Asserts.fail("登录失败");
        }
        return null;
    }

    @Override
    public Map<String, Object> doLogin(String token) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                "LTAI5tEAB8fZ8RhTYGW7rzfk", "IxxCdD3V5fThtsCxNonYa7f2DCW6t9");
        IAcsClient client = new DefaultAcsClient(profile);
        GetMobileRequest request = new GetMobileRequest();
        request.setSysMethod(MethodType.POST);
        request.setActionName("GetMobile");
        request.setSysVersion("2017-05-25");
        request.setAccessToken(token);
        request.putQueryParameter("RegionId", "cn-hangzhou");
        GetMobileResponse response = null;
        String phone = null;
        long start = System.currentTimeMillis();
        try {
            response = client.getAcsResponse(request);
            if (!StringUtils.isEmpty(response)&&"OK".equals(response.getCode())) {
                phone = response.getGetMobileResultDTO().getMobile();
                UmsMemberExample example = new UmsMemberExample();
                example.createCriteria().andUsernameEqualTo(phone);
                List<UmsMember> umsMembers = memberMapper.selectByExample(example);
                if (umsMembers.size() == 0) {
                    //没有绑定用户请前往绑定
                    Map<String,Object> map = new HashMap();
                    map.put("state", "1");
                    map.put("token", "");
                    map.put("phone", phone);
                    return map;
                } else {
                    UmsMember umsMember = umsMembers.get(0);
                    UserDetails userDetails = loadUserByUsername(umsMember.getUsername());
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    token = jwtTokenUtil.generateToken(userDetails);
                    //已经绑定用户信息直接登录
                    Map<String,Object> map = new HashMap();
                    map.put("state", "2");
                    map.put("token", token);
                    map.put("phone", phone);
                    map.put("userInfo", userDetails.getUsername());
                    return map;
                }
            } else {
                Map<String,Object> map = new HashMap();
                map.put("code", StringUtils.isEmpty(response)?null:JSONUtil.toJsonStr(response.getCode()));
                map.put("message", StringUtils.isEmpty(response)?null:JSONUtil.toJsonStr(response.getMessage()));
                return map;
            }
        } catch (ServerException e) {
            log.error(""+e);
            Asserts.fail("登录失败");
        } catch (ClientException e) {
            log.error(""+e);
            Asserts.fail("登录失败");
        } finally {
            log.debug("request:{},response:{},phone:{},cost:{}",
                    JSONUtil.toJsonStr(request),
                    JSONUtil.toJsonStr(response),
                    JSONUtil.toJsonStr(phone),
                    (System.currentTimeMillis() - start));
        }
        return null;
    }

    @Override
    public Map<String, Object> doBindLogin(MemberVO request) {
        Map<String, Object> tokenMap = new HashMap<>();
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(request.getUsername());
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers) || umsMembers.size() >= 1) {
            UmsMember umsMember = umsMembers.get(0);
            UserDetails userDetails = loadUserByUsername(umsMember.getUsername());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String token = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", token);
            tokenMap.put("userInfo", umsMember.getUsername());
            return tokenMap;
        }

        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(request.getUsername());
        if (!StrUtil.isEmpty(request.getPassword())) {
            umsMember.setPassword(passwordEncoder.encode(request.getPassword()));
        }
        umsMember.setPhone(request.getUsername());
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        umsMember.setName(request.getName());
        umsMember.setIdCard(request.getIdCard());
        umsMember.setProvince(request.getProvince());
        umsMember.setArea(request.getCountyCode());
        umsMember.setFloor(request.getFloor());
        umsMember.setCommunityId(request.getCommunityId());
        umsMember.setCommunityName(request.getCommunityName());
        umsMember.setUserType("01");
        umsMember.setCity(request.getCityCode());
        umsMember.setGender(request.getGender());

        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        UmsMemberLog build = UmsMemberLog.builder().userId(umsMember.getId().toString()).name(request.getName()).phone(request.getUsername()).
                idCard(request.getIdCard()).province(request.getProvince()).city(request.getCityCode()).area(request.getCountyCode())
                .status("01").communityId(StringUtils.isEmpty(request.getCommunityId())?null:request.getCommunityId().longValue()).communityName(request.getCommunityName())
                .completePage(request.getCompletePage()).build();
        umsMemberLogService.saveNotNull(build);
        UserDetails userDetails = loadUserByUsername(umsMember.getUsername());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(userDetails);
        //已经绑定用户信息直接登录
        Map<String,Object> map = new HashMap();
        map.put("token", token);
        map.put("userInfo", userDetails.getUsername());
        return map;
    }

}
